package cn.sccdlg.mybatis.dao;

import cn.sccdlg.mybatis.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/13 23:44
 * mybatis主配置文件的优化配置使用方式测验
 */
public class UserDaoTest2 {
    private static final Logger logger =Logger.getLogger(UserDaoTest2.class);

    private InputStream in;
    private SqlSession session;
    private UserDao userDao;

    @Before /** 用于在测试执行方法之前 */
    public void init() throws IOException{
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig2.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        userDao = session.getMapper(UserDao.class);
    }

    @After /** 用于在测试执行方法之后 */
    public void destroy() throws IOException{
        // 提交事务
        session.commit();
        //6.释放资源
        session.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {
        logger.info("测试查询所有方法开始。。。");
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        logger.info("测试查询所有方法结束。。。");
    }


}